package com.hmall.gateway.filter;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> {
    @Override
    public GatewayFilter apply(Config config) {
        GatewayFilter gatewayFilter = new GatewayFilter() {
            // 这个方法是真正执行过滤逻辑的方法 这个实现全局过滤器简直一模一样
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                System.out.println("print any filter running");
                System.out.println("config.a = " + config.a);
                System.out.println("config.b = " + config.b);
                System.out.println("config.c = " + config.c);
                return chain.filter(exchange);
            }
        };
        // 这个是给过滤器设置优先级的，值越小优先级越高
        // 可有可无，不设置默认是0
        return new OrderedGatewayFilter(gatewayFilter, 1);
    }

    PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }

    @Data
    public static class Config {
        private String a;
        private String b;
        private String c;
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("a", "b", "c");
    }
}
